﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;

namespace WgpgCore
{
    public sealed class JpegImage : IDisposable
    {
        private String _filename;
        private Boolean _isTemporary;

        public JpegImage(String filename)
        {
            _filename = filename;
            _isTemporary = false;
            JpegPath = null;

            String tmp = EnsureIsJpegImage(_filename, out _isTemporary);

            if (tmp == null)
                throw new InvalidImageException(filename);

            JpegPath = tmp;
        }

        public String JpegPath { get; private set; }

        public void Dispose()
        {
            Clean();
        }

        ~JpegImage()
        {
            Clean();
        }

        private void Clean()
        {
            try
            {
                if (_isTemporary && JpegPath != null)
                {
                    _isTemporary = false;
                    File.Delete(JpegPath);
                }

                _filename = null;
                JpegPath = null;
            }
            catch
            {
                // Nothing todo
            }
        }

        private static String EnsureIsJpegImage(String filename, out Boolean isTemporaryFile)
        {
            isTemporaryFile = false;

            if (String.IsNullOrEmpty(filename))
                return null;

            try
            {
                using (Image image = Image.FromFile(filename, true))
                {
                    String temp;
                    if (image.RawFormat.Equals(ImageFormat.Jpeg))
                        temp = filename;
                    else
                    {
                        temp = Utils.GetTempFileName();
                        isTemporaryFile = true;
                        image.Save(temp, ImageFormat.Jpeg);
                    }

                    return temp;
                }
            }
            catch
            {
                return null;
            }
        }
    }
}
